#include "HttpProtocol.hpp"
#include "JsonAPI.hpp"
#define WWWROOT "./wwwroot/"

std::string RequestStr(const HttpRequest &req) {
    std::stringstream ss;
    ss << req._request_method << " " << req._source_path << " " << req._version << "\r\n";
    for (auto &it : req._params) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    ss << "测试成功";
    return ss.str();
}

void Test_get(const HttpRequest &req, HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}

void sys_status(HttpProtocol &server, const HttpRequest &req, HttpResponse *rsp){
    
    //创建一个Json对象
    Json::Value resp;
    std::string resp_msg;
    std::string sys_info;
    //读取系统状态信息
    Util::ReadFile("sys_status.txt", &sys_info);
    std::vector<std::string> sys_arr;
    Util::Split(sys_info,"&", &sys_arr);
    //读取线程连接数
    std::vector<uint64_t> threads = server.GetEventLoopConnectCount();

    if (sys_arr.size() >= 5) {
        resp["cpuUsage"] = std::stod(sys_arr[0]);
        resp["memoryUsage"] = std::stod(sys_arr[2]);
        resp["totalMemory"] = std::stod(sys_arr[1]);
        resp["networkSent"] = std::stod(sys_arr[3]);
        resp["networkReceived"] = std::stod(sys_arr[4]);
    }else{
        log_message(ERROR, "从系统状态信息文件中读取失败，此次发送取消");
    }

    for (size_t i = 0; i < threads.size(); ++i) {
        Json::Value thread;
        thread["id"] = static_cast<Json::UInt64>(i + 1); // 序号从1开始
        thread["connectionCount"] = static_cast<Json::UInt64>(threads[i]);
        resp["threads"].append(thread);
    }

    //将json进行序列化并发送
    Json_API::serialize(resp, resp_msg);
    rsp->_statu_code = 200;
    //允许跨域进行资源访问
    rsp->SetHeader("Access-Control-Allow-Origin", "*");
    rsp->SetHeader("Access-Control-Allow-Methods", "GET");
    rsp->SetContent(resp_msg, "application/json");

}


// void Test_post(const HttpRequest &req, HttpResponse *rsp) 
// {
//     rsp->SetContent(RequestStr(req), "text/plain");
// }

// void PutFile(const HttpRequest &req, HttpResponse *rsp) 
// {
//     std::string pathname = WWWROOT + req._source_path;
//     Util::WriteFile(pathname, req._content_body);
//     rsp->_statu_code = 200;
// }

// void Test_del(const HttpRequest &req, HttpResponse *rsp) 
// {
//     rsp->SetContent(RequestStr(req), "text/plain");
// }
int main()
{
    HttpProtocol server(8085);
    server.SetThreadCount(15);
    server.SetBaseDir(WWWROOT);//设置静态资源根目录，告诉服务器有静态资源请求到来，需要到哪里去找资源文件
    server.Get("/test_get", Test_get);
    //如果想传入更多的参数，可以使用lambda，这里不能用Bind，因为包装器要求被传入对象可拷贝
    //但是使用bind，会绑定server的引用，导致bind生成的对应不可拷贝。
    server.Get("/sys_status", [&server](const HttpRequest &req, HttpResponse *rsp) {
        sys_status(server, req, rsp);
    });
    // server.Post("/test_post", Test_post);
    // server.Put("/test.txt", PutFile);
    // server.Delete("/test_del", Test_del);
    server.Listen();
    return 0;
}